//
//  AppDelegate.m
//  Dresshere
//
//  Created by 张朋 on 2017/12/5.
//  Copyright © 2017年 张朋. All rights reserved.
//

#import "AppDelegate.h"
#import "DHHomeViewController.h"
#import "DHNoLoginViewController.h"
#import "DHADViewController.h"
#import "DHTabBarViewController.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import "DHBindingPhoneVC.h"
#import "DHLoginInfoViewController.h"
#import "DHLoginStyleViewController.h"
#import "DHNoticeViewController.h"

#import <BeeCloud/BeeCloud.h>

//微信SDK头文件
#import "WXApi.h"
//新浪微博SDK头文件

#import <UMAnalytics/MobClick.h>        // 统计组件
#import <UMErrorCatch/UMErrorCatch.h>
#import <UMCommon/UMCommon.h>

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

//网易七鱼
#import <QIYU_iOS_SDK/QYSDK.h>

#import <SDWebImage/SDImageCache.h>

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [JPUSHService resetBadge];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    NSDictionary *filter_dic = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SALE_FILTER];
    if (!filter_dic) {
        filter_dic = [NSMutableDictionary dictionary];
        [[NSUserDefaults standardUserDefaults] setObject:filter_dic forKey:USER_SALE_FILTER];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    [self configADController];
//    if ([Login isLogin]) {
//        [self configHomeController];
//    }else{
//        [self configLoginController];
//    }
    [self appConfig];
    [self configBeeCloud];
    [self configShareSDK];
    [self configUM];
    [self configQiYu];
    [self configJPushOptions:launchOptions];
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)appConfig{
    
    [[UITextField appearance] setTintColor:[UIColor colorWithHexString:@"#707070"]];
    [[UITabBar appearance] setTintColor:[UIColor colorWithHexString:@"#575757"]];
    
    
//    [[UITableView appearance] setAllowsSelection:NO];
    
    [[AddressManager shareAddressManager] updateCurrentLocationAndBlock:^(id data, NSError *error) {
        
    }];
    [[GlobalManager shareGlobalManager] refreshVersion];
    [[GlobalManager shareGlobalManager] refreshSupportCities];
    [[GlobalManager shareGlobalManager] refreshlogistics];
    if ([Login isLogin]) {
        [[GlobalManager shareGlobalManager] refreshBasicInfoAndBlock:^(id data, NSError *error) {
            
        }];
        [[GlobalManager shareGlobalManager] refreshDepositAndBlock:^(id data, NSError *error) {
            
        }];
        [[GlobalManager shareGlobalManager] refreshVIPInfoAndBlock:^(id data, NSError *error) {
            
        }];
        [[GlobalManager shareGlobalManager] refreshCartNumberAndBlock:^(id data, NSError *error) {
            
        }];
    }
}

// BeeCloud
- (void)configBeeCloud{
    [BeeCloud initWithAppID:BEECLOUD_APPID andAppSecret:BEECLOUD_LIVE_SECRET sandbox:NO];
    [BeeCloud initWeChatPay:WX_KEY];
}

// 友盟统计
- (void)configUM{
    [UMConfigure initWithAppkey:UM_KEY channel:@"App Store"];
    [UMErrorCatch initErrorCatch];
    [MobClick setScenarioType:E_UM_NORMAL];
}

// 网易七鱼
- (void)configQiYu{
    [[QYSDK sharedSDK] registerAppId:QIYU_KEY appName:@"dresshere"];
}

- (void)configShareSDK{
    [ShareSDK registerActivePlatforms:@[@(SSDKPlatformTypeSinaWeibo),@(SSDKPlatformTypeWechat)]
                             onImport:^(SSDKPlatformType platformType){
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:WB_KEY
                                           appSecret:WB_SECRET
                                         redirectUri:@"http://www.sharesdk.cn"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:WX_KEY
                                       appSecret:WX_SECRET];
                 break;
             default:
                 break;
         }
     }];
}

// 极光推送
- (void)configJPushOptions:(NSDictionary *)launchOptions{
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions
                           appKey:JPUSH_KEY
                          channel:@"App Store"
                 apsForProduction:NO
            advertisingIdentifier:advertisingId];
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support - 前台通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"userInfo:::%@",userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    
    if (![[userInfo objectForKey:@"category"] isEqualToString:@"NOTIFY_ARTICLE"]) {
        if ([Login isLogin]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"order_status_change" object:[userInfo objectForKey:@"orderId"]];
        }
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"userInfo:::%@",userInfo);
    DHNoticeViewController *noticeController = [[DHNoticeViewController alloc] init];
    [[self getCurrentVC].navigationController pushViewController:noticeController animated:YES];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

//handleOpenUrl
//为保证从支付宝，微信返回本应用，须绑定openUrl. 用于iOS9之前版本
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if (![BeeCloud handleOpenUrl:url]) {
        //handle其他类型的url
    }
    return YES;
}
//iOS9之后apple官方建议使用此方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    if (![BeeCloud handleOpenUrl:url]) {
        //handle其他类型的url
    }
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - Config Root Controller
- (void)configADController{
    DHADViewController *adVC = [[DHADViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:adVC];
    nav.navigationBar.hidden = YES;
    self.window.rootViewController = nav;
}

- (void)configHomeController{
    User *user = [Login curLoginUser];
    if (user) {
        if (user.phone.length == 0) {
            DHBindingPhoneVC *bindingController = [[DHBindingPhoneVC alloc] init];
            self.window.rootViewController = bindingController;
        }else{
//            if ([Login curLoginUser].height == 0 || [Login curLoginUser].weight == 0 || [Login curLoginUser].age == 0) { // 身高、体重、年龄未设置
//                DHLoginInfoViewController *infoController = [[DHLoginInfoViewController alloc] init];
//                self.window.rootViewController = infoController;
//            }else if ([Login curLoginUser].styles.count == 0){ // 风格未设置
//                DHLoginStyleViewController *styleController = [[DHLoginStyleViewController alloc] init];
//                self.window.rootViewController = styleController;
//            }else if (![Login curLoginUser].sex){
//                // 这种情况应该是不存在的
//            }
//            else{
                DHTabBarViewController *tabBarController = [DHTabBarViewController new];
                self.window.rootViewController = tabBarController;
//            }
        }
    }else{
        DHTabBarViewController *tabBarController = [DHTabBarViewController new];
        self.window.rootViewController = tabBarController;
    }
}

- (void)configLoginController{
    DHNoLoginViewController *noLoginVC = [[DHNoLoginViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:noLoginVC];
    navController.navigationBarHidden = YES;
    
    typedef void (^Animation)(void);
    UIWindow* window = self.window;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        window.rootViewController = navController;
        [UIView setAnimationsEnabled:oldState];
    };
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:nil];
}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}

@end
